import sys
from PyQt5.QtCore import QDir
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QFileDialog, QMessageBox,QPlainTextEdit
from PyQt5.QtGui import QFont
import xml.etree.ElementTree as ET
import pandas as pd

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("解析xml")
        self.setFixedSize(450, 400)
        self.buttonAnalysis = QPushButton("解析xml文件", self)
        self.buttonOpenMulti = QPushButton("打开多个xml文件", self)
        self.buttonAnalysis.setGeometry(180, 20, 150, 30)
        self.buttonOpenMulti.setGeometry(25, 20, 150, 30)
        self.plainText = QPlainTextEdit(self)
        self.plainText.setEnabled(False)
        self.plainText.setGeometry(25, 60, 400, 300)
        self.buttonAnalysis.clicked.connect(self.analysis_xml_file)
        self.buttonOpenMulti.clicked.connect(self.OpenMulti)
        self.buttonAnalysis.setEnabled(False)
        self.xmlParamList = []
        self.xmlDictList = []
        self.outputPath = QDir.currentPath() + "/output.xlsx"
        self.tree = None
        self.root = None
        self.fileList = None
        self.writer = None

    def OpenMulti(self):
        dlgTitle = "选择一个文件"  # 对话框标题
        filt = "*.xml"  # 文件过滤器
        self.fileList, filtUsed = QFileDialog.getOpenFileNames(self, dlgTitle, QDir.currentPath(), filt)
        self.ChangeEnableButton(True)
        for i in self.fileList:
            self.plainText.appendPlainText(i)

    def ChangeEnableButton(self, flag):
        self.buttonAnalysis.setEnabled(flag)
        self.buttonOpenMulti.setEnabled(flag)

    def analysis_xml_file(self):
        self.ChangeEnableButton(False)
        if self.writer is not None:
            self.writer = None
        for i in self.fileList:
            self.xmlDictList.clear()
            self.AnalysisParam(i)
            self.AnalysisText()
            self.coverToExcel(i)
        self.writer.close()
        dlgTitle = "Info"
        strInfo = "文件解析完成."
        QMessageBox.information(self, dlgTitle, strInfo)
        self.ChangeEnableButton(True)

    def AnalysisParam(self, file):
        self.tree = ET.parse(file)
        self.root = self.tree.getroot()
        for testcase in self.root.findall('.//capltestcase'):
            for param in testcase.findall('caplparam'):
                param_name = param.get('name')
                if param_name not in self.xmlParamList:
                    self.xmlParamList.append(param_name)

    def AnalysisText(self):
        for testcase in self.root.findall('.//capltestcase'):
            tempDict = {"TestcaseFunc": testcase.get('name'), "TestcaseTitle": testcase.get('title')}
            for param in testcase.findall('caplparam'):
                param_name = param.get('name')
                for name in self.xmlParamList:
                    if param_name == name:
                        if name not in tempDict:
                            tempDict[name] = param.text
            self.xmlDictList.append(tempDict)

    def coverToExcel(self, file):
        df = pd.DataFrame(self.xmlDictList)
        if self.writer is None:
            self.writer = pd.ExcelWriter(self.outputPath, engine='xlsxwriter')
        targetSheetName = file.split('/')[-1].split(".")[0][-10:]
        df.to_excel(self.writer,sheet_name=targetSheetName, index=False)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
